﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TheSimGer
{
    static class Program
    {
        static string GetExceptionMsg(Exception ex, string backStr)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("****************************异常文本****************************");
            sb.AppendLine("【出现时间】：" + DateTime.Now.ToString());
            if (ex != null)
            {
                sb.AppendLine("【异常类型】：" + ex.GetType().Name);
                sb.AppendLine("【异常信息】：" + ex.Message);
                sb.AppendLine("【堆栈调用】：" + ex.StackTrace);

                sb.AppendLine("【异常方法】：" + ex.TargetSite);

            }
            else
            {
                sb.AppendLine("【未处理异常】：" + backStr);
            }
            sb.AppendLine("***************************************************************");
            return sb.ToString();
        }

        static string ErrorFolderName = "GameError";
        /// <summary>
        /// 写文件
        /// </summary>
        /// <param name="str"></param>
        public static void writeLog(string str)
        {
            try
            {
                if (!Directory.Exists(ErrorFolderName))
                {
                    Directory.CreateDirectory(ErrorFolderName);
                }

                using (StreamWriter sw = new StreamWriter(ErrorFolderName + "\\ErrLog.txt", true))
                {
                    sw.WriteLine("[" + DateTime.Now.ToLocalTime().ToString() + "]:" + str);
                    sw.WriteLine("---------------------------------------------------------");
                    sw.Close();
                }
            }
            catch
            {
                //日志写入错误自动忽略
                ;
            }
        }

        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            string str = GetExceptionMsg(e.ExceptionObject as Exception, e.ToString());
            writeLog(str);
            // 后续处理，保存或输出
        }

        public static PlayerDongCount MotherForm = null;
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(MotherForm=new PlayerDongCount { StartPosition= FormStartPosition.CenterScreen });
        }
    }
}
